<script setup lang="ts">
import { checkboxEmits } from 'element-plus'
import { getOptions } from '../../../utils/index.ts'
import type { FormItemTool } from '../../../types/index.ts'
import CheckboxAll from './CheckboxAll.vue'

type IProps = {
  item: FormItemTool<'checkBox'>
  allDisabled: boolean
  isEditByRow: boolean

}
const { item, allDisabled, isEditByRow } = defineProps<IProps>()

const labelKey = computed(() => item?.config?.props?.label || 'label')
const valueKey = computed(() => item?.config?.props?.value || 'value')

const value = defineModel<any>('value')
const elRef = useTemplateRef('elRef')

const options = computed(() => getOptions(item))
const currentOption = computed(() => {
  return value.value.map((val: any) => {
    let option = options.value.find((item) => item[valueKey.value] === val)
    if(!option) option = { [labelKey.value]: val, [valueKey.value]: val }
    return option
  })
})

const getRef = () => {
  return elRef.value
}
defineExpose({
  getRef,
})
defineEmits(checkboxEmits)
</script>
<template>
<span>
  <template v-if="isEditByRow">
    <CheckboxAll v-if="item.config?.checkAll" v-bind="typeof item.config?.checkAll === 'object' ? item.config?.checkAll : {}" :options="options" v-model="value"></CheckboxAll>
    <el-checkbox-group
      ref="elRef"
      :disabled="allDisabled"
      v-model="value"
      v-bind="item.config"
      v-on="item.eventFunction || {}"
      v-if="item.isGroup"
    >
      <el-checkbox
        v-for="option in options"
        :key="option.key ?? option[valueKey]"
        :value="option[valueKey]"
        v-bind="item.optionConfig ?? {}"
      >
        {{ option[labelKey] }}
      </el-checkbox>
      <template v-for="slotName in item.slotNames" #[slotName]="slotData">
        <slot :name="slotName" :slotData="slotData"> </slot>
      </template>
    </el-checkbox-group>
    <template v-else>
      <el-checkbox
        v-for="option in options"
        v-model="value"
        :key="option.key ?? option[valueKey]"
        :disabled="allDisabled"
        v-bind="item.config"
        v-on="item.eventFunction || {}"
      >
        {{ option[labelKey] }}
      </el-checkbox>
    </template>
  </template>
  <span v-else> {{ currentOption.map((item: any) => item[labelKey]).join(',') }} </span>
</span>
</template>

<style scoped lang="scss">
</style>
